<template>
  <div class="collection-page">
    <el-page-header content="我的收藏" @back="handleBack" />
    
    <el-card class="collection-card" v-if="collectionList.length > 0">
      <el-table 
        :data="collectionList" 
        border 
        style="width: 100%"
        :empty-text="loading ? '加载中...' : '暂无收藏数据'"
      >
        <el-table-column prop="collectionId" label="收藏ID" width="100" align="center" />
        
        <!-- 设备图片：点击跳转详情 -->
        <el-table-column label="设备图片" width="120" align="center">
          <template #default="scope">
            <div 
              class="image-container" 
              @click="handleContainerClick(scope.row)"
              style="cursor: pointer"
            >
              <el-image 
                :src="scope.row.equipment.equipmentImages[0]?.imageUrl" 
                :preview-src-list="getImageList(scope.row)"
                fit="cover" 
                class="equipment-image"
                fallback-src="https://cube.elemecdn.com/e/fd/0fc7d205b3291b96bce9e488e0edbfb.png"
              />
            </div>
          </template>
        </el-table-column>
        
        <!-- 设备信息：点击跳转详情 -->
        <el-table-column label="设备信息" align="center">
          <template #default="scope">
            <div 
              class="equipment-info" 
              @click="handleContainerClick(scope.row)"
              style="cursor: pointer"
            >
              <div class="brand-model">
                <span class="brand">{{ scope.row.equipment.brand }}</span>
                <span class="model">{{ scope.row.equipment.model }}</span>
              </div>
              <div class="year-hour">
                <span>年份: {{ scope.row.equipment.year }}</span>
                <span>工作小时: {{ scope.row.equipment.hour }}h</span>
              </div>
              <div class="location">
                <el-icon><Location /></el-icon>
                <span>{{ scope.row.equipment.location }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="equipment.price" label="价格" width="120" align="center">
          <template #default="scope">
            <span class="price">¥{{ scope.row.equipment.price.toLocaleString() }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="collectionTime" label="收藏时间" width="180" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.collectionTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(scope.row.collectionId)"
              :loading="deleteLoading[scope.row.collectionId]"
              class="delete-btn"
            >
              <el-icon><Delete /></el-icon>
              <span>删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <div v-else-if="!loading" class="empty-collection">
      <el-empty description="暂无收藏的设备" />
      <el-button type="primary" @click="handleBack" style="margin-top: 16px;">
        <el-icon><ArrowLeft /></el-icon>返回设备列表
      </el-button>
    </div>
    
    <el-loading v-if="loading" fullscreen text="加载中..." />
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { useCounterStore } from '@/stores/counter';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Location, ArrowLeft, Delete } from '@element-plus/icons-vue';
// 导入路由实例（确保项目中已配置路由）
import router from '@/router';

// 状态管理
const userStore = useCounterStore();
const userId = userStore.userId;

// 响应式数据
const collectionList = ref([]);
const loading = ref(true);
const deleteLoading = ref({});

// 获取图片列表用于预览
const getImageList = (row) => {
  return row.equipment.equipmentImages.map(img => img.imageUrl);
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 点击设备图片/信息，跳转设备详情页
const handleContainerClick = (ref) => {
  console.log('eq', ref.equipment.equipmentId);
  // 跳转到详情页面（路由name为"Shang"）
  router.push({
    name: 'Shang',
    params: {
      equipmentId: ref.equipment.equipmentId // 从设备对象中获取equipmentId
    }
  });
};

// 获取收藏列表
const fetchCollections = async () => {
  try {
    loading.value = true;
    const res = await axios.get(`/eduservice/collection/getCollectionByUserId2/${userId}`);
    if (res.data.success) {
      collectionList.value = res.data.data.list || [];
    } else {
      ElMessage.error(res.data.message || '获取收藏列表失败');
    }
  } catch (error) {
    console.error('获取收藏列表出错:', error);
    ElMessage.error('网络错误，获取收藏列表失败');
  } finally {
    loading.value = false;
  }
};

// 删除收藏
const handleDelete = async (collectionId) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消收藏该设备吗？',
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    deleteLoading.value[collectionId] = true;
    const res = await axios.delete(`/eduservice/collection/deleteCollectionById/${collectionId}`);
    
    if (res.data.success) {
      ElMessage.success('取消收藏成功');
      // 重新获取收藏列表
      fetchCollections();
    } else {
      ElMessage.error(res.data.message || '取消收藏失败');
    }
  } catch (error) {
    if (error.name !== 'Error') { // 排除取消确认的错误
      console.error('删除收藏出错:', error);
      ElMessage.error('网络错误，取消收藏失败');
    }
  } finally {
    deleteLoading.value[collectionId] = false;
  }
};

// 返回上一页
const handleBack = () => {
  window.history.back();
};

// 页面挂载时获取数据
onMounted(() => {
  fetchCollections();
});
</script>

<style scoped>
.collection-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.collection-card {
  margin-top: 20px;
}

.equipment-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
}

/* 图片容器 hover 效果，提示可点击 */
.image-container:hover .equipment-image {
  opacity: 0.9;
  box-shadow: 0 0 8px rgba(24, 144, 255, 0.3);
}

.equipment-info {
  padding: 5px 0;
}

/* 设备信息 hover 效果，提示可点击 */
.equipment-info:hover {
  color: #1890ff;
}

.brand-model {
  margin-bottom: 8px;
}

.brand {
  font-weight: bold;
  margin-right: 10px;
  color: #1890ff;
}

.model {
  color: #666;
}

.year-hour {
  margin-bottom: 4px;
  font-size: 13px;
  color: #666;
}

.year-hour span {
  margin-right: 15px;
}

.location {
  font-size: 12px;
  color: #999;
  display: flex;
  align-items: center;
}

.location span {
  margin-left: 5px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.empty-collection {
  margin-top: 50px;
  text-align: center;
}

/* 删除按钮样式，确保图标和文字对齐 */
.delete-btn {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}
</style>